package com.example.springboot_demo.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description: 实现 拦截器的方法
 * 记录接口访问的总时长
 * <P> Date: 2024/6/22:17:20
 */

@SuppressWarnings({"unchecked", ""})
@Component
public class MyInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(MyInterceptor.class);
    /**
     * 存储当前接口的开始访问时间
    */
    ThreadLocal<Long> stareTime = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        request.getHeader("Authorization");
        String agent = request.getHeader("user-agent");
        long now = System.currentTimeMillis();
        stareTime.set(now);

        log.info("进入前置拦截器:user-agent:{}", agent);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("controller 调用完毕");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long end = System.currentTimeMillis();
        log.info("afterCompletion 执行,本次请求执行时长：{} ms", end - stareTime.get());
        stareTime.remove();
    }
}
